<?php

use app\common\model\Category;
use fast\Form;
use fast\Tree;
use think\Db;

/**
 * 生成下拉列表
 * @param string $name
 * @param mixed $options
 * @param mixed $selected
 * @param mixed $attr
 * @return string
 */
function build_select($name, $options, $selected = [], $attr = [])
{
    $options = is_array($options) ? $options : explode(',', $options);
    $selected = is_array($selected) ? $selected : explode(',', $selected);
    return Form::select($name, $options, $selected, $attr);
}

/**
 * 生成单选按钮组
 * @param string $name
 * @param array $list
 * @param mixed $selected
 * @return string
 */
function build_radios($name, $list = [], $selected = null)
{
    $html = [];
    $selected = is_null($selected) ? key($list) : $selected;
    $selected = is_array($selected) ? $selected : explode(',', $selected);
    foreach ($list as $k => $v)
    {
        $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::radio($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
    }
    return '<div class="radio">' . implode(' ', $html) . '</div>';
}

/**
 * 生成复选按钮组
 * @param string $name
 * @param array $list
 * @param mixed $selected
 * @return string
 */
function build_checkboxs($name, $list = [], $selected = null)
{
    $html = [];
    $selected = is_null($selected) ? [] : $selected;
    $selected = is_array($selected) ? $selected : explode(',', $selected);
    foreach ($list as $k => $v)
    {
        $html[] = sprintf(Form::label("{$name}-{$k}", "%s {$v}"), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
    }
    return '<div class="checkbox">' . implode(' ', $html) . '</div>';
}

/**
 * 生成分类下拉列表框
 * @param string $name
 * @param string $type
 * @param mixed $selected
 * @param array $attr
 * @return string
 */
function build_category_select($name, $type, $selected = null, $attr = [], $header = [])
{
    $tree = Tree::instance();
    $tree->init(Category::getCategoryArray($type), 'pid');
    $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
    $categorydata = $header ? $header : [];
    foreach ($categorylist as $k => $v)
    {
        $categorydata[$v['id']] = $v['name'];
    }
    $attr = array_merge(['id' => "c-{$name}", 'class' => 'form-control selectpicker'], $attr);
    return build_select($name, $categorydata, $selected, $attr);
}

/**
 * 生成表格操作按钮栏
 * @param array $btns 按钮组
 * @param array $attr 按钮属性值
 * @return string
 */
function build_toolbar($btns = NULL, $attr = [])
{
    $auth = \app\admin\library\Auth::instance();
    $controller = str_replace('.', '/', strtolower(think\Request::instance()->controller()));
    $btns = $btns ? $btns : ['refresh', 'add', 'edit', 'del', 'import'];
    $btns = is_array($btns) ? $btns : explode(',', $btns);
    $index = array_search('delete', $btns);
    if ($index !== FALSE)
    {
        $btns[$index] = 'del';
    }
    $btnAttr = [
        'refresh' => ['javascript:;', 'btn btn-primary btn-refresh', 'fa fa-refresh', '', __('Refresh')],
        'add'     => ['javascript:;', 'btn btn-success btn-add', 'fa fa-plus', __('Add'), __('Add')],
        'edit'    => ['javascript:;', 'btn btn-success btn-edit btn-disabled disabled', 'fa fa-pencil', __('Edit'), __('Edit')],
        'del'     => ['javascript:;', 'btn btn-danger btn-del btn-disabled disabled', 'fa fa-trash', __('Delete'), __('Delete')],
        'import'  => ['javascript:;', 'btn btn-danger btn-import', 'fa fa-upload', __('Import'), __('Import')],
    ];
    $btnAttr = array_merge($btnAttr, $attr);
    $html = [];
    foreach ($btns as $k => $v)
    {
        //如果未定义或没有权限
        if (!isset($btnAttr[$v]) || ($v !== 'refresh' && !$auth->check("{$controller}/{$v}")))
        {
            continue;
        }
        list($href, $class, $icon, $text, $title) = $btnAttr[$v];
        $extend = $v == 'import' ? 'id="btn-import-' . \fast\Random::alpha() . '" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"' : '';
        $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" ' . $extend . '><i class="' . $icon . '"></i> ' . $text . '</a>';
    }
    return implode(' ', $html);
}

/**
 * 生成页面Heading
 *
 * @param string $path 指定的path
 * @return string
 */
function build_heading($path = NULL, $container = TRUE)
{
    $title = $content = '';
    if (is_null($path))
    {
        $action = request()->action();
        $controller = str_replace('.', '/', request()->controller());
        $path = strtolower($controller . ($action && $action != 'index' ? '/' . $action : ''));
    }
    // 根据当前的URI自动匹配父节点的标题和备注
    $data = Db::name('auth_rule')->where('name', $path)->field('title,remark')->find();
    if ($data)
    {
        $title = __($data['title']);
        $content = __($data['remark']);
    }
    if (!$content)
        return '';
    $result = '<div class="panel-lead"><em>' . $title . '</em>' . $content . '</div>';
    if ($container)
    {
        $result = '<div class="panel-heading">' . $result . '</div>';
    }
    return $result;
}
function build_sn($address)
{
    //API控制台申请得到的ak（此处ak值仅供验证参考使用）
    $ak = 'Qblrt1BGVDYFUBho94vE2isqMrfT2fxZ';

    //应用类型为for server, 请求校验方式为sn校验方式时，系统会自动生成sk，可以在应用配置-设置中选择Security Key显示进行查看（此处sk值仅供验证参考使用）
    $sk = 'nGajvBxqbwLYk4OqL2s2jcLTBmNGzk8z';

    //以Geocoding服务为例，地理编码的请求url，参数待填
    $url = "http://api.map.baidu.com/geocoder/v2/?address=%s&output=%s&ak=%s&sn=%s";

    //get请求uri前缀
    $uri = '/geocoder/v2/';

    //地理编码的请求中address参数
   // $address = '百度大厦';

    //地理编码的请求output参数
    $output = 'json';

    //构造请求串数组
    $querystring_arrays = [
        'address' => $address,
        'output' => $output,
        'ak' => $ak
    ];

    //调用sn计算函数，默认get请求
    $sn = caculateAKSN($ak, $sk, $uri, $querystring_arrays);

    //请求参数中有中文、特殊字符等需要进行urlencode，确保请求串与sn对应
    $target = sprintf($url, urlencode($address), $output, $ak, $sn);

    $result = postCurl($target,'get');
    if($result['status'] == 0)
    {
        return $result['result']['location'];
    }
    return ['lng'=>null,'lat'=>null];
}

function caculateAKSN($ak, $sk, $url, $querystring_arrays, $method = 'GET')
{  
    if ($method === 'POST'){  
        ksort($querystring_arrays);  
    }  
    $querystring = http_build_query($querystring_arrays);  
    return md5(urlencode($url.'?'.$querystring.$sk));  
}
/**
 *$this->postCurl方法
 */
function postCurl($url,$type="POST"){
    //1.创建一个curl资源
    $ch = curl_init();
    //2.设置URL和相应的选项
    curl_setopt($ch,CURLOPT_URL,$url);//设置url
    //1)设置请求头
    //array_push($header, 'Accept:application/json');
    //array_push($header,'Content-Type:application/json');
    //array_push($header, 'http:multipart/form-data');
    //设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
    curl_setopt($ch,CURLOPT_HEADER,0);
//      curl_setopt ( $ch, CURLOPT_TIMEOUT,5); // 设置超时限制防止死循环
    //设置发起连接前的等待时间，如果设置为0，则无限等待。
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
    //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //上传文件相关设置
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 从证书中检查SSL加密算
    
    //3)设置提交方式
    switch($type){
        case "GET":
            curl_setopt($ch,CURLOPT_HTTPGET,true);
            break;
        case "POST":
            curl_setopt($ch,CURLOPT_POST,true);
            break;
        case "PUT"://使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请求。这对于执行"DELETE" 或者其他更隐蔽的HTT
            curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"PUT");
            break;
        case "DELETE":
            curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"DELETE");
            break;
    }
    
    //4)在HTTP请求中包含一个"User-Agent: "头的字符串。-----必设

//      curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
//      curl_setopt($ch, CURLOPT_ENCODING, 'gzip');

    curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器
    //5)
    
    //3.抓取URL并把它传递给浏览器
    $res=curl_exec($ch);


    $result=json_decode($res,true);
    //4.关闭curl资源，并且释放系统资源
    curl_close($ch);
    if(empty($result))
        return $res;
    else
        return $result;
}
